﻿var LogView = LogView || {};

$.extend(LogView, function () {

    function updatePartial(target, params, selector) {

        var response = makeCall(target, params);

        if (response.d.Status == "OK") {
            $(selector).empty();
            $(selector).html(response.d.Message);
        }
    }

    function makeCall(target, params, callback) {

        if (params == undefined)
            params = {};

        var response;
        var doAsync = (callback != undefined);

        $.ajax({
            type: "POST",
            url: target,
            data: JSON.stringify(params),
            async: doAsync,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                response = msg;
                if (callback != undefined)
                    callback(msg);
            }
        });

        if (doAsync)
            return;

        if (response == undefined)
            response = { d: { Status: "FAIL", Message: "Something went wrong with the call"} };

        if (response.d.Status != 'OK') {
            if (response.d.Message != undefined) {
                alert(response.d.Message);
            }
            else {
                alert('Something went very wrong');
            }
        }

        return response;

    };

    // http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
    function queryString(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    return {
        MakeCall: makeCall,
        UpdatePartial: updatePartial,
        QueryString: queryString
    };
} ());


